package com.moshang.blog.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.moshang.blog.entity.ThirdLogin;
import com.moshang.blog.mapper.ThirdLoginMapper;
import com.moshang.blog.service.ThirdLoginService;
import com.moshang.blog.core.utils.HttpUtil;
import com.moshang.blog.core.utils.JsonUtil;
import com.moshang.blog.core.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

import static com.alipay.api.AlipayConstants.CHARSET;

/**
 * @program: blog
 * @description: ${description}
 * @author: xieweiwei
 * @create: 2018-10-18 10:50
 **/
@Service("thirdLoginService")
public class ThirdLoginServiceImpl implements ThirdLoginService {
    /**
     *   获取qq token地址
     */

    public static String QQ_TOKEN_URL = "https://graph.qq.com/oauth2.0/token";
    /**
     *   获取qq openId 地址
     */

    public static String QQ_OPENID_URL = "https://graph.qq.com/oauth2.0/me";
    /**
     *   获取qq 用户信息 地址
     */

    public static String QQ_USERINFO_URL = "https://graph.qq.com/user/get_user_info";
    public static String PRIVATEKEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA07b8tuj3Bt1B3qsIefkpb6413eAkx6/nev444gbJaPfEu467FlzQkGwV23zueT2XRbEdTVdZhZHgUf1SyaLzjOg6qUQiUFFk7l0tpUYn1x5vtiIC6OT1o6Z4Szv4y4bV18TU1PXM7xeiDRC9WEqSolIapqtJhJ+WV/hwt4tZYq4EJmQdzQyWMytRHfLbBmJ49pQNCxMY9u3n10XhSalMbnviQ2KCAa1y8Nd/bMuuZR0CjefcIAXIf10/t/+P7iF57PU7C+1V0nUi6Oxcxo0+FFAwRl+WccUv5Q72qmy4zA0KCle2WBg1svteQVVnG40SWLD+6/HnTZqaQfRatLPAtwIDAQAB";
    public static String PUBLICKEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA07b8tuj3Bt1B3qsIefkpb6413eAkx6/nev444gbJaPfEu467FlzQkGwV23zueT2XRbEdTVdZhZHgUf1SyaLzjOg6qUQiUFFk7l0tpUYn1x5vtiIC6OT1o6Z4Szv4y4bV18TU1PXM7xeiDRC9WEqSolIapqtJhJ+WV/hwt4tZYq4EJmQdzQyWMytRHfLbBmJ49pQNCxMY9u3n10XhSalMbnviQ2KCAa1y8Nd/bMuuZR0CjefcIAXIf10/t/+P7iF57PU7C+1V0nUi6Oxcxo0+FFAwRl+WccUv5Q72qmy4zA0KCle2WBg1svteQVVnG40SWLD+6/HnTZqaQfRatLPAtwIDAQAB";
    @Resource
    private ThirdLoginMapper thirdLoginMapper;
    @Override
    public ThirdLogin getInFo() {
        QueryWrapper<ThirdLogin> thirdLogin=new QueryWrapper();
        return thirdLoginMapper.selectOne(thirdLogin);
    }

    @Override
    public Map<String, String> getTokenAsstoken(String code) {
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put("client_id", getInFo().getQqAppId());
        formMap.put("client_secret", getInFo().getQqAppKey());
        formMap.put("grant_type", "authorization_code");
        formMap.put("redirect_uri", getInFo().getQqRedictUrl());
        formMap.put("code", code);
        String result = HttpUtil.post(QQ_TOKEN_URL, formMap);
        Map<String, String> map = StringUtils.getParam(result);
        map.put("access_token",map.get("access_token"));
        return map;
    }

    @Override
    public Map<String, String> getOpenId(String access_token) {
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put("access_token", access_token);
        String result = HttpUtil.post(QQ_OPENID_URL, formMap);
        String newResult=result.replace("callback(","").replace(")\n","");
        Map<String, String> resultMap = JsonUtil.toObject(newResult, HashMap.class, Map.class, String.class, String.class);
        // callback({"client_id":"YOUR_APPID","openid":"YOUR_OPENID"})
        Map<String,String> map=new HashMap<>();

        map.put("openid",resultMap.get("openid"));
        return map;
    }

    @Override
    public Map<String, String> getUserInfo(String access_token, String openid) {
        String url = new StringBuilder(QQ_USERINFO_URL)
                .append("?access_token=").append(access_token)
                .append("&oauth_consumer_key=").append(getInFo().getQqAppId())
                .append("&openid=").append(openid).toString();
        String result = HttpUtil.get(url);
        Gson gson = new Gson();
        Map<String, String> resultMap= new HashMap<>();
        resultMap = gson.fromJson(result, resultMap.getClass());
        return resultMap;
    }

    @Override
    public String getAliAccessToken(String code) {
        ThirdLogin thirdLogin = getInFo();
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", thirdLogin.getAliAppId(), PRIVATEKEY, "json", CHARSET, PUBLICKEY, "RSA2");
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        request.setCode(code);
        request.setGrantType("authorization_code");
        try {
            AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(request);
            System.out.println(oauthTokenResponse.getAccessToken());
            return oauthTokenResponse.getAccessToken();
        } catch (AlipayApiException e) {
            //处理异常
            e.printStackTrace();
        }
        return null;
    }

}
